<template>
  <div class="moving-path">
    <v-main>
      <div class="store-summary">
        <el-row class="summary-main clearfix">
          <el-col :span="8" style="margin-right:20px;">
            <el-date-picker :clearable="false"
                            v-model="choosenDate"
                            type="daterange"
                            size="mini"
                            value-format="yyyy-MM-dd"
                            @change = "changeDateRange"
                            :picker-options="pickerOptions"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
          <el-col :span="8" class="time_options">
            <span :class="[{ active: activeDateOption === 'first' }, 'option']" @click="handleDate('yesterday')">昨天</span>
            <span :class="[{ active: activeDateOption === 'second' }, 'option']" @click="handleDate('sevenDay')">7天</span>
            <span :class="[{ active: activeDateOption === 'third' }, 'option']" @click="handleDate('fourteenDay')">14天</span>
            <span :class="[{ active: activeDateOption === 'fourth' }, 'option']" @click="handleDate('thirtyDay')">30天</span>
          </el-col>
        </el-row>
      </div>
      <div class="title">动线路径图</div>
      <div class="moving-branch">
        <div class="filter-wrapper clearfix">
          <div class="filter">
            <label class="desc">起始区域:</label>
            <el-select class="selector"
                       v-model="currPickerAreaId"
                       @change="changeArea"
                       size="mini"
                       placeholder="区域筛选">
              <el-option
                v-for="item in areaOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <label class="desc">性别:</label>
            <el-select class="selector"
                       v-model="currPickerGender"
                       @change="changeGender"
                       size="mini"
                       placeholder="性别筛选">
              <el-option
                v-for="(item, index) in genderOptions"
                :key="index"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <label class="desc">年龄:</label>
            <el-select class="selector"
                       v-model="currPickerAge"
                       @change="changeAge"
                       size="mini"
                       placeholder="年龄筛选">
              <el-option
                v-for="item in ageOptions"
                :key="item.value"
                :label="item.label"
                :data = "ageOptions"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="branch-box">
          <div class="tips">
            <span>
              <i class="el-icon-warning"></i>
              点击对应区域可查看区域路径过程
            </span>
          </div>
          <div class="area-width clearfix">
            <div class="area-wrapper clearfix">
              <div class="nodata-tips" v-if="!totalTimes">
                您的选择暂无数据，请重新选择
              </div>
              <div v-else class="area-column" v-for="(value, key) in areaData" :key="key">
                <div :class="[{ active:  area.isActive }, { gone: area.isGone }, 'area-info']"
                     v-for="(area, inx) in value"
                     :key="inx"
                     @click="getNextArea(key, area)">
                  <div class="total-times" v-if="key === 0">
                    <span class="total-desc">{{area.last_zone_name}}</span>
                    <span class="total-num">{{area.amount}}</span>
                    <i class="el-icon-d-arrow-right arrow" v-show="area.isActive"></i>
                  </div>
                  <div class="area" v-else>
                    <span class="detail">{{area.amount === 0 ? '0.00%' : ((Math.round(area.amount / totalTimes * 10000) / 100.00).toFixed(2) + "%")}} {{`(${area.amount}人)`}}</span>
                    <span class="detail">{{area.last_zone_name}}</span>
                    <i class="el-icon-d-arrow-right arrow" v-show="area.isActive"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </v-main>
  </div>
</template>

<script type="text/ecmascript-6">
import Main from '@/components/main'
import { Row, Col, DatePicker, Select, Option } from 'element-ui'
import Moment from 'moment'
import { mapGetters } from 'vuex'

// api
import { APIGetMoveLineBranch } from '@/api/trajectory.js'

export default {
  name: 'LinePath',
  components: {
    // elementUI component
    elRow: Row,
    elCol: Col,
    elDatePicker: DatePicker,
    elSelect: Select,
    elOption: Option,
    vMain: Main
  },

  created () {
    this.APIGetMoveLineBranch(this.choosenDate[0], this.choosenDate[1])
  },

  data () {
    return {
      currAccount: 0,
      totalTimes: 0,
      activeDateOption: 'first',
      choosenDate: [Moment().subtract(1, 'day').format('YYYY-MM-DD'), Moment().subtract(1, 'day').format('YYYY-MM-DD')],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Moment().subtract(1, 'day')
        }
      },
      currPickerAreaId: 0,
      genderOptions: [
        {
          value: 0,
          label: '不限'
        },
        {
          value: 1,
          label: '男'
        },
        {
          value: 2,
          label: '女'
        }
      ],
      currPickerGender: 0,
      currPickerAge: 0,
      currAgeArr: [0, 100],
      ageOptions: [
        {
          value: 0,
          range: [0, 100],
          label: '不限'
        },
        {
          value: 1,
          range: [0, 17],
          label: '小于18岁'
        },
        {
          value: 2,
          range: [18, 23],
          label: '18-23岁'
        },
        {
          value: 3,
          range: [24, 30],
          label: '24-30岁'
        },
        {
          value: 4,
          range: [31, 40],
          label: '31-40岁'
        },
        {
          value: 5,
          range: [41, 50],
          label: '41-50岁'
        },
        {
          value: 6,
          range: [51, 60],
          label: '51-60岁'
        },
        {
          value: 7,
          range: [61, 100],
          label: '大于60岁'
        }
      ],
      areaData: []
    }
  },

  computed: {
    ...mapGetters([
      'mallId',
      'mallMapData'
    ]),
    areaOptions () {
      let options = this.mallMapData.map((item) => { return { 'name': item.name, 'footprints_hash': '', 'id': item.id } })
      options.unshift({'name': '全部', 'footprints_hash': '', 'id': 0})
      return options
    }
  },

  methods: {
    // 用户选择时间
    changeDateRange () {
      this.filterChange()
    },
    handleDate (option) {
      // b 昨天
      let b = Moment().subtract(1, 'day').format('YYYY-MM-DD')
      switch (option) {
        case 'yesterday':
          if (this.activeDateOption !== 'first') {
            this.activeDateOption = 'first'
            this.choosenDate = [b, b]
            this.filterChange()
          }
          break
        case 'sevenDay':
          if (this.activeDateOption !== 'second') {
            this.activeDateOption = 'second'
            // c 7天前
            let c = Moment().subtract(7, 'day').format('YYYY-MM-DD')
            this.choosenDate = [c, b]
            this.filterChange()
          }
          break
        case 'fourteenDay':
          if (this.activeDateOption !== 'third') {
            this.activeDateOption = 'third'
            // d 14天前
            let d = Moment().subtract(14, 'day').format('YYYY-MM-DD')
            this.choosenDate = [d, b]
            this.filterChange()
          }
          break
        case 'thirtyDay':
          if (this.activeDateOption !== 'fourth') {
            this.activeDateOption = 'fourth'
            // e 30天前
            let e = Moment().subtract(30, 'day').format('YYYY-MM-DD')
            this.choosenDate = [e, b]
            this.filterChange()
          }
          break
        default:
          this.activeDateOption = 'first'
          this.choosenDate = [b, b]
          this.filterChange()
          break
      }
    },
    // 过滤器选择
    changeArea () {
      this.filterChange()
    },
    changeGender () {
      this.filterChange()
    },
    changeAge () {
      this.currAgeArr = (this.ageOptions.filter((item) => item.value === this.currPickerAge))[0]['range']
      this.filterChange()
    },
    getNextArea (key, area) {
      if (!area.isActive && area.footprints_hash !== '') {
        this.areaData[key].forEach(item => { item.isActive = false })
        this.areaData.splice(key + 1)
        // 改变状态 并且记录要到下一级的total
        area.isActive = true
        this.currAccount = area.amount
        // 发送请求
        this.APIGetMoveLineBranch(this.choosenDate[0], this.choosenDate[1], this.currAgeArr[0], this.currAgeArr[1], this.currPickerGender, area.footprints_hash, area.last_zone_id)
      }
    },
    filterChange () {
      this.areaData = []
      this.APIGetMoveLineBranch(this.choosenDate[0], this.choosenDate[1], this.currAgeArr[0], this.currAgeArr[1], this.currPickerGender)
    },
    // get data api
    APIGetMoveLineBranch (startDate, endDate, startAge, endAge, gender, parentHash, zoneId) {
      APIGetMoveLineBranch({shop: this.mallId, startDate, endDate, startAge, endAge, gender, parentHash})
        .then((res) => {
          res.data.stats.forEach((item) => { item['isActive'] = false })
          if (this.areaData.length === 0) {
            this.totalTimes = (res.data.stats.map((item) => item.amount)).reduce((x, y) => x + y, 0)
            this.areaData[0] = [ {total: true, amount: this.totalTimes, last_zone_name: '统计人次', isActive: true, footprints_hash: ''} ]
            if (this.currPickerAreaId !== 0) {
              this.areaData = []
              let currArea = (res.data.stats.filter((item) => item.last_zone_id === this.currPickerAreaId))[0]
              this.totalTimes = currArea.amount
              this.areaData[0] = [ {amount: this.totalTimes, last_zone_name: '统计人次', isActive: true, footprints_hash: ''} ]
              this.areaData[1] = [{ amount: this.totalTimes, last_zone_name: currArea.last_zone_name, isActive: false, footprints_hash: currArea.footprints_hash, last_zone_id: currArea.last_zone_id }]
              return
            }
          }
          //  增加离开店铺
          if (this.areaData.length >= 2 && zoneId) {
            let sum = (res.data.stats.map((item) => item.amount)).reduce((x, y) => x + y, 0)
            let rest = this.currAccount - sum
            res.data.stats.push({amount: rest, last_zone_name: '离开店铺', isGone: true, footprints_hash: ''})
            let filterArea = res.data.stats.filter((item) => item.last_zone_id !== zoneId)
            this.areaData.push(filterArea)
            return
          }
          this.areaData.push(res.data.stats)
        })
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
  // scoped
  .moving-path {
    .summary-main {
      padding: 10px 0;
      .time_options{
        height: 32px;
        line-height: 32px;
        .option{
          margin-right: 20px;
          font-size: 14px;
          color: black;
          cursor: pointer;
          &.active{
            color: rgb(30, 184, 39);
          }
        }
      }
    }
    .title {
      margin: 10px 0;
    }
    .moving-branch {
      border: 1px solid #e4e7ed;;
      .filter-wrapper {
        padding: 15px 20px;
        border-bottom: 1px solid #e4e7ed;;
        .filter {
          float: right;
          right: 0;
          .desc{
            font-size: 12px;
          }
          .selector {
            width: 150px;
            &:not(:last-child){
              margin-right: 15px;
            }
          }
        }
      }
      .branch-box {
        padding: 20px;
        .area-width {
          width: 100%;
          height: 500px;
          margin-top: 20px;
          .area-wrapper {
            height: 500px;
            display: flex;
            align-items: center;
            overflow: auto;
            .nodata-tips {
              position: absolute;
              left: 50%;
              transform: translateX(-50%);
            }
            .area-column {
              min-width: 150px;
              max-width: 150px;
              float: left;
              margin-right: 10px;
              padding: 10px;
              .area-info {
                position: relative;
                width: 100%;
                height: auto;
                font-size: 14px;
                margin-bottom: 10px;
                white-space: normal;
                border: 1px solid black;
                background-color: #d2ecd0;
                .total-times {
                  .total-desc {
                    display: inline-block;
                    width: 100%;
                    height: 40px;
                    line-height: 40px;
                    font-size: 20px;
                    text-align: center;
                    color: #fff;
                    background-color: #1aad19;
                    border-bottom: 1px solid black;
                  }
                  .total-num {
                    display: inline-block;
                    width: 100%;
                    height: 65px;
                    line-height: 65px;
                    font-size: 40px;
                    text-align: center;
                    background-color: #d2ecd0;
                  }
                }
                .area {
                  padding-left: 10px;
                }
              &.active {
                background-color: #1aad19;
              }
              &.gone {
                background-color: #f7d8d6;
              }
                .arrow {
                  font-size: 14px;
                  color: black;
                  position: absolute;
                  right: -22px;
                  bottom: 50%;
                  transform: translateY(50%);
                }
                .detail {
                  display: inline-block;
                  width: 100%;
                  height: 30px;
                  line-height: 30px;
                  text-align: left;
                }
                &:last-child {
                  margin-bottom: 0px;
                }
              }
            }
          }
        }
      }
    }
  }
</style>
